package com.yuyou.fn.portal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wens.mq.MessageHandler;
import com.github.wens.mq.RedisMessageQueue;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.JSONS;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.CourseClass;
import com.yuyou.fn.educational.entity.CourseOrder;
import com.yuyou.fn.educational.entity.Student;
import com.yuyou.fn.educational.entity.StudentReg;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.service.impl.CourseOrderServiceImpl;
import com.yuyou.fn.educational.vo.RegClassInfoVo;
import com.yuyou.fn.educational.vo.StudentRegInfoVo;
import com.yuyou.fn.portal.entity.OuterCourseClass;
import com.yuyou.fn.portal.entity.OuterShoppingcart;
import com.yuyou.fn.portal.service.IOuterCourseClassService;
import com.yuyou.fn.portal.service.IOuterShoppingcartService;
import com.yuyou.fn.portal.vo.ClassInfoVo;
import com.yuyou.fn.portal.vo.CourseClassResultVo;
import com.yuyou.fn.portal.vo.OrderCourseClass;
import com.yuyou.fn.portal.vo.OuterCourseOrderVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import com.yuyou.fn.portal.mapper.OuterCourseOrderMapper;
import com.yuyou.fn.portal.entity.OuterCourseOrder;
import com.yuyou.fn.portal.service.IOuterCourseOrderService;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 *
 * OuterCourseOrder 表数据服务层接口实现类
 *
 */
@Service
public class OuterCourseOrderServiceImpl extends SuperServiceImpl<OuterCourseOrderMapper, OuterCourseOrder,Long> implements IOuterCourseOrderService {
    @Resource
    private ICourseOrderService courseOrderService;

    @Resource
    private ICourseClassService courseClassService;

    @Resource
    private IStudentService studentService;

    @Resource
    private IStudentRegService studentRegService;

    @Resource
    private ICustomerUserService customerUserService;

    @Resource
    private IOuterShoppingcartService outerShoppingcartService;

    @Resource
    private IOuterCourseClassService outerCourseClassService;


    @Resource
    private RedisMessageQueue redisMessageQueue ;

    @Resource
    private IOuterCourseOrderService outerCourseOrderService;

    @PostConstruct
    public void init(){
        redisMessageQueue.consume("order:pay:success:mobileCourseOrder", new MessageHandler() {
            @Override
            public void onMessage(byte[] bytes) {
                JSONObject jsonObject = JSONS.toJSONObject(bytes);
                Long courseOrderId  = jsonObject.getLong("busId");
                BigDecimal amount = jsonObject.getBigDecimal("amount");
                OuterCourseOrderServiceImpl.this.payOuterCourseOrder(courseOrderId,amount,4,null);
            }
        });
    }

    @Transactional
    @Override
    public void payOuterCourseOrder(Long outerCourseOrderId,BigDecimal payAmount, Integer payWay,Long userId) {
       // String userName=customerUserService.findById(userId).getUsername();
        List<CourseOrder> courseOrderList = courseOrderService.findCourseOrderByOutId(outerCourseOrderId);
        for (CourseOrder courseOrder : courseOrderList) {
            courseOrderService.payCourseOrder(courseOrder.getCourseOrderId(), courseOrder.getTotalAmount(), payWay, null);
        }
        //处理大单
        OuterCourseOrder outerCourseOrder = this.findById(outerCourseOrderId);
        if(outerCourseOrder.getPayableAmount().compareTo(payAmount)>0){
            throw new  BusException("付款金额小于应付金额");
        }
        outerCourseOrder.setPaidAmount(outerCourseOrder.getPayableAmount());
        outerCourseOrder.setChargingStatus(2);
        this.updateSelectiveById(outerCourseOrder);

    }

    @Override
    public List<OrderCourseClass> findOuterCourseOrder(Long userId,int pageNo,int pageSize) {
        Example<OuterCourseOrder> example=OuterCourseOrder.createExample();
       // example.selectProperties("classId");
        example.createCriteria().andEqualTo("userId",userId);

        Page<OuterCourseOrder> page=findPageByExample(example,pageNo,pageSize);
        List<OuterCourseOrder> outerCourseOrderList=page.getRecords();
        List<OrderCourseClass> list=new ArrayList<OrderCourseClass>();
        for(OuterCourseOrder outerCourseOrder:outerCourseOrderList){
            OrderCourseClass orderCourseClass=new OrderCourseClass();
            String orderData=outerCourseOrder.getOrderData();
            List<ClassInfoVo> classInfoVoList=JSONObject.parseArray(orderData,ClassInfoVo.class);
            for (ClassInfoVo classInfoVo:classInfoVoList){
                CourseClassResultVo courseClassResultVo=classInfoVo.getCourseClass();
                if (StringUtils.isEmpty(courseClassResultVo.getCampusName()) || StringUtils.isEmpty(courseClassResultVo.getTeacherIds()) ||
                        StringUtils.isEmpty(courseClassResultVo.getRoomName())) {
                    courseClassResultVo=outerCourseClassService.findDetailByClassId(courseClassResultVo.getClassId());
                    classInfoVo.setCourseClass(courseClassResultVo);
                }
            }

            BeanUtils.copyProperties(orderCourseClass,outerCourseOrder);
            orderCourseClass.setClassInfoList(classInfoVoList);
            list.add(orderCourseClass);
        }
        return list;
    }

    @Override
    public CourseOrder createCourseOrder(Long classId, Long studentId, Long userId) {
        StudentRegInfoVo studentRegInfoVo=new StudentRegInfoVo();
        CourseClass courseClass=courseClassService.findById(classId);
        if(courseClass==null) throw  new BusException("找不到该课程");
        studentRegInfoVo.setStudentId(studentId);
        studentRegInfoVo.setFrom(1);//线上
        studentRegInfoVo.setOperator(userId+"");
        RegClassInfoVo regClassInfoVo=new RegClassInfoVo();
        regClassInfoVo.setClassId(classId);
        regClassInfoVo.setStartAmount(1);
        regClassInfoVo.setEndAmount(courseClass.getLectureAmount());
        List<RegClassInfoVo> list=new ArrayList<RegClassInfoVo>();
        list.add(regClassInfoVo);
        studentRegInfoVo.setRegClassInfoList(list);
        CourseOrder courseOrder = courseOrderService.createOrder(studentRegInfoVo);
        return  courseOrder;
    }




    @Override
    @Transactional
    public OrderCourseClass createOuterCourseOrder(Long classId, String studentIds,Long userId) {
        OuterCourseOrder outerCourseOrder=new OuterCourseOrder();
        outerCourseOrder.setOuterCourseOrderId(IdWorker.getId());

        String[] studentIdList=studentIds.split(",");
        int length=studentIdList.length;
     //   StringBuffer studentNames = new StringBuffer();
      //  StringBuffer studentIdBuff = new StringBuffer();
        BigDecimal totalAmount = new BigDecimal(0);
        BigDecimal payableAmount = new BigDecimal(0);
        String preffix = ",";
        StringBuffer courseOrderIds=new StringBuffer();
        List<ClassInfoVo> classInfoVoList=new ArrayList<ClassInfoVo>();
        ClassInfoVo classInfoVo=new ClassInfoVo();
        CourseClassResultVo courseClassResultVo=outerCourseClassService.findDetailByClassId(classId);
        classInfoVo.setCourseClass(courseClassResultVo);
        OuterCourseClass outerCourseClass=new OuterCourseClass();
        BeanUtils.copyProperties(outerCourseClass,courseClassResultVo);
        if (courseClassResultVo==null) throw new BusException("不存在该课程");
        List<Student> studentList=new ArrayList<Student>();
        try {
            for (int i=0;i<length;i++){
                if(i==length-1) preffix="";
                String studentId=studentIdList[i];
                Student student=studentService.findById(Long.parseLong(studentId));
                if (student==null) throw new  BusException("不存在该学生");
                List<Long> classIds = new ArrayList<Long>();
                List<StudentReg> studentRegs = studentRegService.findStudentClassIds(Long.parseLong(studentId), Arrays.asList("0"));
                for (StudentReg studentReg : studentRegs) {
                    classIds.add(studentReg.getClassId());
                }
                List<OuterCourseClass> outerCourseClasses = outerCourseClassService.findByClassIds(classIds);
                String check=outerShoppingcartService.checkClassTime(Arrays.asList(outerCourseClass),outerCourseClasses);
                if (!"ok".equals(check)) {
                    throw new BusException(check);
                } else {
                    studentList.add(student);
                    CourseOrder courseOrder = this.createCourseOrder(classId, Long.parseLong(studentId), userId);
                    courseOrder.setOuterCourseOrderId(outerCourseOrder.getOuterCourseOrderId());
                    courseOrderService.updateSelectiveById(courseOrder);
                    payableAmount = payableAmount.add(courseOrder.getPayableAmount());
                    totalAmount = totalAmount.add(courseOrder.getTotalAmount());
                    courseOrderIds.append(courseOrder.getCourseOrderId() + preffix);

                    //清除购物车记录的人员
                    OuterShoppingcart outerShoppingcart=outerShoppingcartService.findOuterShoppingcartByCondition(userId,Long.parseLong(studentId),classId);
                    if(outerShoppingcart!=null){
                        String cartStudentIds=outerShoppingcart.getStudentIds();
                        cartStudentIds=cartStudentIds.replace(studentId+",","");
                        cartStudentIds=cartStudentIds.replace(","+studentId,"");
                        cartStudentIds=cartStudentIds.replace(studentId,"");
                        OuterShoppingcart outerShoppingcart1=new OuterShoppingcart();
                        outerShoppingcart1.setOuterShoppingcartId(outerShoppingcart.getOuterShoppingcartId());
                        outerShoppingcart1.setStudentIds(cartStudentIds);
                        outerShoppingcartService.updateSelectiveById(outerShoppingcart1);
                    }
                }

            }
        }catch (Exception e){
            throw new BusException(e.getMessage());
        }

        classInfoVo.setStudentList(studentList);
        classInfoVoList.add(classInfoVo);

        outerCourseOrder.setCreateTime(TimeUtils.now());
        outerCourseOrder.setCreateTime(TimeUtils.now());
        outerCourseOrder.setChargingStatus(0);//未缴费
        outerCourseOrder.setPaidAmount(new BigDecimal(0));
        outerCourseOrder.setPayableAmount(payableAmount);
        outerCourseOrder.setTotalAmount(totalAmount);
        outerCourseOrder.setUserId(userId);
        outerCourseOrder.setCourseOrderIds(courseOrderIds.toString());
        outerCourseOrder.setOrderData(JSONObject.toJSONString(classInfoVoList));
        this.insertSelective(outerCourseOrder);

        OrderCourseClass orderCourseClass=new OrderCourseClass();
        orderCourseClass.setChargingStatus(outerCourseOrder.getChargingStatus());
        orderCourseClass.setOuterCourseOrderId(outerCourseOrder.getOuterCourseOrderId());
        orderCourseClass.setTotalAmount(outerCourseOrder.getTotalAmount());
        orderCourseClass.setClassInfoList(classInfoVoList);




        return orderCourseClass;
    }

    @Override
    @Transactional
    public OrderCourseClass createOuterCourseOrder(List<Long> outerShoppingCartIds, Long userId) {
        List<OuterShoppingcart> outerShoppingcartList=outerShoppingcartService.findByIds(outerShoppingCartIds);
        OuterCourseOrder outerCourseOrder=new OuterCourseOrder();
        outerCourseOrder.setOuterCourseOrderId(IdWorker.getId());
        BigDecimal totalAmount = new BigDecimal(0);
        BigDecimal payableAmount = new BigDecimal(0);
        String preffix = ",";
        StringBuffer courseOrderIds=new StringBuffer();
        List<ClassInfoVo> classInfoVoList=new ArrayList<ClassInfoVo>();
        if(outerShoppingcartList.size()<=0) throw new BusException("该购物车不存在");
        try {
            for (int j = 0; j < outerShoppingcartList.size(); j++) {
                OuterShoppingcart outerShoppingcart = outerShoppingcartList.get(j);
                if (outerShoppingcart.getStudentIds() != null && !"".equals(outerShoppingcart.getStudentIds())) {
                    String[] studentIdList = outerShoppingcart.getStudentIds().split(",");
                    Long classId = outerShoppingcart.getClassId();
                    ClassInfoVo classInfoVo = new ClassInfoVo();
                    CourseClassResultVo courseClassResultVo = outerCourseClassService.findDetailByClassId(classId);
                    classInfoVo.setCourseClass(courseClassResultVo);
                    List<Student> studentList = new ArrayList<Student>();
                    int length = studentIdList.length;
                    for (int i = 0; i < length; i++) {
                        if (i == length - 1 && j == outerShoppingcartList.size() - 1) preffix = "";
                        String studentId = studentIdList[i];
                        Student student = studentService.findById(Long.parseLong(studentId));
                        studentList.add(student);
                        CourseOrder courseOrder = this.createCourseOrder(classId, Long.parseLong(studentId), userId);
                        courseOrder.setOuterCourseOrderId(outerCourseOrder.getOuterCourseOrderId());
                        courseOrderService.updateSelectiveById(courseOrder);
                        payableAmount = payableAmount.add(courseOrder.getPayableAmount());
                        totalAmount = totalAmount.add(courseOrder.getTotalAmount());
                        courseOrderIds.append(courseOrder.getCourseOrderId() + preffix);
                    }
                    classInfoVo.setStudentList(studentList);
                    classInfoVoList.add(classInfoVo);
                } else {
                    throw new BusException("存在课程没有选择学员");
                }
            }
        } catch (Exception e) {
            throw new BusException(e.getMessage());
        }

        outerCourseOrder.setCreateTime(TimeUtils.now());
        outerCourseOrder.setCreateTime(TimeUtils.now());
        outerCourseOrder.setChargingStatus(0);//未缴费
        outerCourseOrder.setPaidAmount(new BigDecimal(0));
        outerCourseOrder.setPayableAmount(payableAmount);
        outerCourseOrder.setTotalAmount(totalAmount);
        outerCourseOrder.setUserId(userId);
        outerCourseOrder.setCourseOrderIds(courseOrderIds.toString());
        outerCourseOrder.setOrderData(JSONObject.toJSONString(classInfoVoList));
        this.insertSelective(outerCourseOrder);
        OrderCourseClass orderCourseClass=new OrderCourseClass();
        orderCourseClass.setChargingStatus(outerCourseOrder.getChargingStatus());
        orderCourseClass.setOuterCourseOrderId(outerCourseOrder.getOuterCourseOrderId());
        orderCourseClass.setTotalAmount(outerCourseOrder.getTotalAmount());
        orderCourseClass.setClassInfoList(classInfoVoList);

        //清除购物车
        Example<OuterShoppingcart> example=OuterShoppingcart.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("userId",userId);
        List<Long> list=new ArrayList<Long>();
        criteria.andIn("outerShoppingcartId",outerShoppingCartIds);
        outerShoppingcartService.deleteByExample(example);
        return orderCourseClass;
    }

    @Override
    public List<OrderCourseClass> findOuterCourseOrder(Long userId, int pageNo, int pageSize, Integer chargingStatus) {
        Example<OuterCourseOrder> example=OuterCourseOrder.createExample();
        // example.selectProperties("classId");
        Example.Criteria criteria=example.createCriteria();

        criteria.andEqualTo("userId",userId);

        criteria.andEqualTo("chargingStatus",chargingStatus);



        Page<OuterCourseOrder> page=findPageByExample(example,pageNo,pageSize);
        List<OuterCourseOrder> outerCourseOrderList=page.getRecords();
        List<OrderCourseClass> list=new ArrayList<OrderCourseClass>();
        for(OuterCourseOrder outerCourseOrder:outerCourseOrderList){
            OrderCourseClass orderCourseClass=new OrderCourseClass();
            String orderData=outerCourseOrder.getOrderData();
            List<ClassInfoVo> classInfoVoList=JSONObject.parseArray(orderData,ClassInfoVo.class);
            for (ClassInfoVo classInfoVo:classInfoVoList){
                CourseClassResultVo courseClassResultVo=classInfoVo.getCourseClass();
                if (StringUtils.isEmpty(courseClassResultVo.getCampusName()) || StringUtils.isEmpty(courseClassResultVo.getTeacherIds()) ||
                        StringUtils.isEmpty(courseClassResultVo.getRoomName())) {
                    courseClassResultVo=outerCourseClassService.findDetailByClassId(courseClassResultVo.getClassId());
                    classInfoVo.setCourseClass(courseClassResultVo);
                }
            }
            BeanUtils.copyProperties(orderCourseClass,outerCourseOrder);
            orderCourseClass.setClassInfoList(classInfoVoList);
            list.add(orderCourseClass);
        }
        return list;
    }

    @Override
    public OrderCourseClass findOuterCourseOrder(Long userId, Long outerCourseOrderId) {
        Example<OuterCourseOrder> example=OuterCourseOrder.createExample();
        // example.selectProperties("classId");
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("userId",userId);
        criteria.andEqualTo("outerCourseOrderId",outerCourseOrderId);
        OuterCourseOrder outerCourseOrder=this.findById(outerCourseOrderId);
        if(outerCourseOrder==null) throw new  BusException("不存在该订单");
        OrderCourseClass orderCourseClass=new OrderCourseClass();
        String orderData=outerCourseOrder.getOrderData();
        List<ClassInfoVo> classInfoVoList=JSONObject.parseArray(orderData,ClassInfoVo.class);
        for (ClassInfoVo classInfoVo:classInfoVoList){
            CourseClassResultVo courseClassResultVo=classInfoVo.getCourseClass();
            if (StringUtils.isEmpty(courseClassResultVo.getCampusName()) || StringUtils.isEmpty(courseClassResultVo.getTeacherIds()) ||
                    StringUtils.isEmpty(courseClassResultVo.getRoomName())) {
                courseClassResultVo=outerCourseClassService.findDetailByClassId(courseClassResultVo.getClassId());
                classInfoVo.setCourseClass(courseClassResultVo);
            }
        }
        BeanUtils.copyProperties(orderCourseClass,outerCourseOrder);
        orderCourseClass.setClassInfoList(classInfoVoList);

        return orderCourseClass;
    }

    @Override
    public List<OuterCourseOrder> findOuterCourseOrder(Integer chargingStatus,Date date) {
        Example<OuterCourseOrder> example=OuterCourseOrder.createExample();
        // example.selectProperties("classId");
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("chargingStatus",chargingStatus);
        criteria.andGreaterThan("createTime",date);
        List<OuterCourseOrder> outerCourseOrderList=this.findListByExample(example);


        return outerCourseOrderList;
    }
}